import { defineStore } from 'pinia'
import { getChapters } from '@/api/book'
import { getBookshelfDb } from '@/utils/localDb'
import bookContract from '@/contracts/db/bookshelfContract'
import { useBookshelfStore } from '@/stores/bookshelf'

export const useBookChapterStore = defineStore('bookChapterStore', () => {
  const bookshelfStore = useBookshelfStore()
  const bookshelf = getBookshelfDb(bookContract.store)

  // 获取书籍章节
  function getBookChapters(bookId) {
    const key = `${bookContract.item.chapters}-${bookId}`

    return bookshelf.getItem(key).then((chapters) => {
      if (chapters && chapters.items.length > 0) {
        return Promise.resolve(chapters.items)
      } else {
        return getChapters(bookId).then((apiRes) => {
          console.log('book-chapters', apiRes)
          bookshelf.setItem(key, apiRes.data)
          return Promise.resolve(apiRes.data.items)
        })
      }
    })
  }

  // 获取书籍的最后阅读章节
  async function getBookLastReadingChapter(bookId) {
    const book = await bookshelfStore.getBook(bookId)
    const chapters = await getBookChapters(bookId)
    let currentChapter = null
    if (book) {
      const lastReadingChapterId = book.lastReadingChapterId
      if (lastReadingChapterId) {
        currentChapter = chapters.find((chapter) => {
          return chapter.id == lastReadingChapterId
        })
      }
    }

    return currentChapter
  }

  // 获取指定书籍的章节
  async function getBookChapter(bookId, chapterId) {
    const chapters = await getBookChapters(bookId)
    const currentChapter = chapters.find((chapter) => {
      return chapter.id == chapterId
    })
    return currentChapter
  }

  return { getBookChapters, getBookLastReadingChapter, getBookChapter }
})
